package com.spark.common.ext

import android.app.Activity
import android.content.ContentResolver
import android.content.ContentUris
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.support.v4.app.Fragment

/**
 * 拍照
 */
fun Activity.takePicture(uri: Uri, requestCode: Int) {
    val intent = Intent()
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        // 对目标应用临时授权该 uri 所代表的文件
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    }
    intent.action = MediaStore.ACTION_IMAGE_CAPTURE
    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
    startActivityForResult(intent, requestCode)
}

/**
 * 打开相册
 */
fun Activity.openGallery(requestCode: Int, type: String = "/image/*") {
    val intent = Intent(Intent.ACTION_GET_CONTENT)
    intent.type = type
    startActivityForResult(intent, requestCode)
}

/**
 * 系统裁剪图片
 */
fun Activity.cropImage(orgUri: Uri, destUri: Uri, aspectX: Int, aspectY: Int, outputX: Int, outputY: Int, requestCode: Int) {
    val intent = Intent("com.android.camera.action.CROP")
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    }
    intent.apply {
        setDataAndType(orgUri, "iamge/*")
        putExtra("crop", true)
        putExtra("aspectX", aspectX)
        putExtra("aspectY", aspectY)
        putExtra("outputX", outputX)
        putExtra("outputY", outputY)
        putExtra("scale", true)

        putExtra(MediaStore.EXTRA_OUTPUT, destUri)
        putExtra("return-data", false)
        putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString())
        putExtra("noFaceDetection", true)
        startActivityForResult(intent, requestCode)
    }
}

/**
 * 从 Uri 中获取 bitmap
 */
fun Context.bitmapFromUri(uri: Uri): Bitmap? {
    return try {
        MediaStore.Images.Media.getBitmap(contentResolver, uri)
    } catch (e: Exception) {
        e.printStackTrace()
        null
    }
}

/**
 * 判断 uri 是否是 MediaProvider 提供的
 */
private fun Uri.isMediaDocument(): Boolean {
    return "com.android.providers.media.documents" == authority
}

/**
 * 判断 uri 是否是 DownloadsProvider 提供的
 */
private fun Uri.isDownloadsDocument(): Boolean {
    return "com.android.providers.downloads.documents" == authority
}

/**
 * 判断 uri 是否是 ExternalStorageProvider 提供的
 */
private fun Uri.isExtStoreDocument(): Boolean {
    return "com.android.externalstorage.documents" == authority
}

/**
 * 从Uri 中获取 dataColumn 行信息
 * 即从 ContentProvider 的数据库中获取行数据
 */
private fun Context.dataColumnFromUri(uri: Uri, selection: String?, selectionArgs: Array<String>?): String {
    val column = "_data"
    val projection = arrayOf(column)
    contentResolver.query(uri, projection, selection, selectionArgs, null)?.apply {
        if (moveToFirst()) {
            val col = getColumnIndexOrThrow(column)
            return getString(col)
        }
        this.close()
    }
    return ""
}

/**
 * 从 uri 中获取文件的设备路径
 */
fun Context.uriPath(uri: Uri?): String {
    if (uri == null) return ""
    val isKitkat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
    // documentProvider
    if (isKitkat && DocumentsContract.isDocumentUri(this, uri)) {
        when {
        // externalStorageProvider
            uri.isExtStoreDocument() -> {
                val docid = DocumentsContract.getDocumentId(uri)
                val docs = docid.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                val type = docs[0]
                if ("primary".equals(type, ignoreCase = true)) {
                    return "${Environment.getExternalStorageDirectory()}/${docs[1]}"
                }
            }
        // downloadsProvider
            uri.isDownloadsDocument() -> {
                val docid = DocumentsContract.getDocumentId(uri)
                val contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), docid.toLong())
                return dataColumnFromUri(contentUri, null, null)
            }
        // mediaProvider
            uri.isMediaDocument() -> {
                val docid = DocumentsContract.getDocumentId(uri)
                val docs = docid.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                val type = docs[0]
                val contentUri = when (type) {
                    "image" -> MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                    "video" -> MediaStore.Video.Media.EXTERNAL_CONTENT_URI
                    "audio" -> MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
                    else -> MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                }
                return dataColumnFromUri(contentUri, "_id=?", arrayOf(docs[1]))
            }
        }
    } else if ("content" == uri.scheme.toLowerCase()) {
        return dataColumnFromUri(uri, null, null)
    } else if ("file" == uri.scheme.toLowerCase()) {
        return uri.path
    }
    return ""
}


/**
 * 获取 resource 资源文件的绝对路径
 * 比如 R.drawable.ic_launcher
 */
fun Context?.relAbsPath(resId: Int): String {
    return if (this.isNull()) ""
    else
        Uri.parse("${ContentResolver.SCHEME_ANDROID_RESOURCE}://" +
                "${this?.resources?.getResourcePackageName(resId)}/" +
                "${this?.resources?.getResourceTypeName(resId)}/" +
                this?.resources?.getResourceEntryName(resId)).toString()
}

/*fun Activity?.relAbsPath(resId: Int): String {
    return if (this.isNull()) ""
    else
        Uri.parse("${ContentResolver.SCHEME_ANDROID_RESOURCE}://" +
                "${this?.resources?.getResourcePackageName(resId)}/" +
                "${this?.resources?.getResourceTypeName(resId)}/" +
                this?.resources?.getResourceEntryName(resId)).toString()
}*/

fun Fragment.relAbsPath(resId: Int): String {
    return Uri.parse("${ContentResolver.SCHEME_ANDROID_RESOURCE}://" +
            "${resources.getResourcePackageName(resId)}/" +
            "${resources.getResourceTypeName(resId)}/" +
            resources.getResourceEntryName(resId)).toString()
}

fun android.app.Fragment.relAbsPath(resId: Int): String {
    return Uri.parse("${ContentResolver.SCHEME_ANDROID_RESOURCE}://" +
            "${resources.getResourcePackageName(resId)}/" +
            "${resources.getResourceTypeName(resId)}/" +
            resources.getResourceEntryName(resId)).toString()
}